package com.example.mylibrary.utils;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.channels.FileChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Hejx on 2017/12/12.
 * 文件操作工具
 */
public class FileUtil {

    public static final String USB_DIR = "/mnt/usb_storage/";

    public static String getUsbStorageDirectory() {
        return USB_DIR;
    }

    /**
     * 外接USB是否启用
     */
    public static boolean isUsbStorageDirectoryEnable() {
        File usb = new File(USB_DIR);
        return usb.canWrite();
    }

    /**
     * 文件是否存在
     */
    public static boolean exists(String path) {
        return !TextUtils.isEmpty(path) && new File(path).exists();
    }

    /**
     * 获取文件大小
     */
    public static long getFileSize(String filePath) {
        return getFileSize(new File(filePath));
    }

    /**
     * 获取文件大小
     */
    public static long getFileSize(File source) {
        long size = 0;
        try {
            File[] files = source.listFiles();
            for (File file : files) {
                size += file.isDirectory() ? getFileSize(file) : file.length();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 创建文件
     */
    public static boolean createFile(String path) {
        return createFile(new File(path));
    }

    /**
     * 创建文件
     */
    public static boolean createFile(File source) {
        if (source.exists() && source.isFile()) {
            return true;
        }
        File parent = source.getParentFile();
        if (!parent.exists() && !parent.mkdirs()) {
            return false;
        }
        try {
            return source.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 创建文件夹
     */
    public static boolean createDirs(String path) {
        return createFile(new File(path));
    }

    /**
     * 创建文件夹
     */
    public static boolean createDirs(File source) {
        return source.exists() && source.isDirectory() || source.mkdirs();
    }

    /**
     * 复制文件
     *
     * @param source       源文件
     * @param target       目标文件
     * @param deleteSource 复制后是否删除源文件
     */
    @SuppressWarnings("ConstantConditions")
    public static boolean copyFile(File source, File target, boolean deleteSource)
            throws IOException {

        FileChannel inChannel = new FileInputStream(source).getChannel();
        FileChannel outChannel = new FileOutputStream(target).getChannel();

        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
            return !deleteSource || source.delete();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (inChannel != null) {
                inChannel.close();
            }
            if (outChannel != null) {
                outChannel.close();
            }
        }
    }

    /**
     * 删除文件
     */
    public static boolean deleteFile(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (String aChildren : children) {
                boolean success = deleteFile(new File(dir, aChildren));
                if (!success) return false;
            }
        }
        return dir.delete();
    }

    /**
     * 文件转byte输出
     *
     * @param imagePath 文件路径
     */
    public static byte[] loadFileAsStream(String imagePath) throws Exception {
        FileInputStream fs = new FileInputStream(imagePath);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();

        byte[] buffer = new byte[1024];
        int len;
        while (-1 != (len = fs.read(buffer))) {
            outStream.write(buffer, 0, len);
        }

        outStream.close();
        fs.close();

        return outStream.toByteArray();
    }

    /**
     * 读取文件转换为字符串
     *
     * @param fileName 文件路径
     */
    public static String loadFileAsString(String fileName) {
        FileReader reader = null;
        try {
            reader = new FileReader(fileName);
            String text = loadReaderAsString(reader);
            reader.close();
            return text;
        } catch (Exception e) {
//            e.printStackTrace();
        }
        return "";
    }

    /**
     * 将FileReader转换为字符串
     *
     * @param reader FileReader对象
     */
    private static String loadReaderAsString(Reader reader) throws Exception {
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[4096];
        int readLength = reader.read(buffer);
        while (readLength >= 0) {
            builder.append(buffer, 0, readLength);
            readLength = reader.read(buffer);
        }
        return builder.toString();
    }

    /**
     * 获取应用专属缓存目录
     * android 4.4及以上系统不需要申请SD卡读写权限
     * 因此也不用考虑6.0系统动态申请SD卡读写权限问题，切随应用被卸载后自动清空 不会污染用户存储空间
     * @param context 上下文
     * @param type 文件夹类型 可以为空，为空则返回API得到的一级目录
     * @return 缓存文件夹 如果没有SD卡或SD卡有问题则返回内存缓存目录，否则优先返回SD卡缓存目录
     */
    public static File getCacheDirectory(Context context,String type) {
        File appCacheDir = getExternalCacheDirectory(context,type);
        if (appCacheDir == null){
            appCacheDir = getInternalCacheDirectory(context,type);
        }

        if (appCacheDir == null){
            Log.e("getCacheDirectory","getCacheDirectory fail ,the reason is mobile phone unknown exception !");
        }else {
            if (!appCacheDir.exists()&&!appCacheDir.mkdirs()){
                Log.e("getCacheDirectory","getCacheDirectory fail ,the reason is make directory fail !");
            }
        }
        return appCacheDir;
    }

    /**
     * 获取SD卡缓存目录
     * @param context 上下文
     * @param type 文件夹类型 如果为空则返回 /storage/emulated/0/Android/data/app_package_name/cache
     *             否则返回对应类型的文件夹如Environment.DIRECTORY_PICTURES 对应的文件夹为 .../data/app_package_name/files/Pictures
     * {@link Environment#DIRECTORY_MUSIC},
     * {@link Environment#DIRECTORY_PODCASTS},
     * {@link Environment#DIRECTORY_RINGTONES},
     * {@link Environment#DIRECTORY_ALARMS},
     * {@link Environment#DIRECTORY_NOTIFICATIONS},
     * {@link Environment#DIRECTORY_PICTURES}, or
     * {@link Environment#DIRECTORY_MOVIES}.or 自定义文件夹名称
     * @return 缓存目录文件夹 或 null（无SD卡或SD卡挂载失败）
     */
    public static File getExternalCacheDirectory(Context context,String type) {
        File appCacheDir = null;
        if( Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            if (TextUtils.isEmpty(type)){
                appCacheDir = context.getExternalCacheDir();
            }else {
                appCacheDir = context.getExternalFilesDir(type);
            }

            if (appCacheDir == null){// 有些手机需要通过自定义目录
                appCacheDir = new File(Environment.getExternalStorageDirectory(),"Android/data/"+context.getPackageName()+"/cache/"+type);
            }

            if (appCacheDir == null){
                Log.e("getExternalDirectory","getExternalDirectory fail ,the reason is sdCard unknown exception !");
            }else {
                if (!appCacheDir.exists()&&!appCacheDir.mkdirs()){
                    Log.e("getExternalDirectory","getExternalDirectory fail ,the reason is make directory fail !");
                }
            }
        }else {
            Log.e("getExternalDirectory","getExternalDirectory fail ,the reason is sdCard nonexistence or sdCard mount fail !");
        }
        return appCacheDir;
    }
    /**
     * 获取内存缓存目录
     * @param type 子目录，可以为空，为空直接返回一级目录
     * @return 缓存目录文件夹 或 null（创建目录文件失败）
     * 注：该方法获取的目录是能供当前应用自己使用，外部应用没有读写权限，如 系统相机应用
     */
    public static File getInternalCacheDirectory(Context context, String type) {
        File appCacheDir = null;
        if (TextUtils.isEmpty(type)){
            appCacheDir = context.getCacheDir();// /data/data/app_package_name/cache
        }else {
            appCacheDir = new File(context.getFilesDir(),type);// /data/data/app_package_name/files/type
        }

        if (!appCacheDir.exists()&&!appCacheDir.mkdirs()){
            Log.e("getInternalDirectory","getInternalDirectory fail ,the reason is make directory fail !");
        }
        return appCacheDir;
    }



    private static final ExecutorService executor = Executors.newSingleThreadExecutor();

    /**
     * 删除指定目录指定前后缀的文件
     *
     * @param dirPath
     * @param isPrefix
     * @param regEx
     */
    public static void delete(String dirPath, boolean isPrefix, String regEx) {
        executor.execute(new DeleteRunnable(dirPath, isPrefix, regEx));
    }
}
